package com.zelma.agent.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.zelma.agent.dao.AgentDao;
import com.zelma.agent.entity.AgentEntity;
import com.zelma.agent.service.AgentService;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zelma.common.utils.PageUtils;
import com.zelma.common.utils.Query;

import com.zelma.agent.dao.CircleDao;
import com.zelma.agent.entity.CircleEntity;
import com.zelma.agent.service.CircleService;


@Service("circleService")
@SuppressWarnings("all")
public class CircleServiceImpl extends ServiceImpl<CircleDao, CircleEntity> implements CircleService {

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private AgentDao agentDao;

    @Override
    public List <CircleEntity> findCircleInfo (String agentName,
                                               String circleContent,
                                               String circleCreatedate) throws IOException, ParseException {

        //同步ES端口
        SearchRequest searchRequest = new SearchRequest("circle");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        //多条件查询
        BoolQueryBuilder builder = new BoolQueryBuilder();
        //每个条件分别查询
        if (agentName!=null && !"".equals(agentName)){
            //根据agentName查询出经纪人
            AgentEntity agentEntity = agentDao.selectOne(new QueryWrapper <AgentEntity>().eq("agent_name", agentName));
            //判断经纪人对象是否为空
            if (agentEntity!=null){
                Integer agentId = agentEntity.getAgentId();
                builder.filter(QueryBuilders.matchQuery("agentId",agentId));
            }
        }
        //判断楼市圈信息是否为空
        if (circleContent!=null && !"".equals(circleContent)){
            builder.filter(QueryBuilders.matchQuery("circleContent",circleContent));
        }
        //判断楼市圈信息创建时间是否为空
        if (circleCreatedate!=null && !"".equals(circleCreatedate)){
            //将字符串类型时间转换为date类型
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = format.parse(circleCreatedate);
            //es中查询类型转换为毫秒值
            builder.filter(QueryBuilders.rangeQuery("circleCreatedate").gte(date.getTime()));
        }

        HighlightBuilder highlightBuilder = new HighlightBuilder();
        HighlightBuilder.Field highlightTitle =
                new HighlightBuilder.Field("circleContent");
        highlightTitle.highlighterType("unified");
        highlightBuilder.preTags("<span style='color:red'><b>");
        highlightBuilder.postTags("</b></span>");
        highlightBuilder.field(highlightTitle);
        searchSourceBuilder.highlighter(highlightBuilder);

        searchSourceBuilder.query(builder);
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);

        SearchHits hits = searchResponse.getHits();
        TotalHits totalHits = hits.getTotalHits();
// the total number of hits, must be interpreted in the context of totalHits.relation
        long numHits = totalHits.value;
// whether the number of hits is accurate (EQUAL_TO) or a lower bound of the total (GREATER_THAN_OR_EQUAL_TO)
        TotalHits.Relation relation = totalHits.relation;
        float maxScore = hits.getMaxScore();
        ArrayList <CircleEntity> list = new ArrayList <>();
        SearchHit[] searchHits = hits.getHits();
        for (SearchHit hit : searchHits) {
            // do something with the SearchHit
            String index = hit.getIndex();
            String id = hit.getId();
            float score = hit.getScore();
            String sourceAsString = hit.getSourceAsString();
            CircleEntity circleEntity = JSON.parseObject(sourceAsString, new TypeReference <CircleEntity>() {
            });
            circleEntity.setCircleId(Integer.valueOf(id));
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField highlight = highlightFields.get("circleContent");
            if (highlight!=null){
                Text[] fragments = highlight.fragments();
                String fragmentString = fragments[0].string();
                circleEntity.setCircleContent(fragmentString);
            }
            list.add(circleEntity);
        }
        return list;
    }

    @Override
    public void eslist () throws IOException {

        List <CircleEntity> list = baseMapper.selectList(null);

        for (CircleEntity circleEntity : list) {
            IndexRequest request = new IndexRequest("circle");
            request.id(String.valueOf(circleEntity.getCircleId()));
            String jsonString = JSONObject.toJSONString(circleEntity);
            request.source(jsonString, XContentType.JSON);
            IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
        }
        System.out.println("楼市圈数据同步ES结束");
    }
}